package com.himiotech.core.project.web.base;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wuwenbin
 */
class DataReqBaseController {

    /**
     * 分页的排序字段
     *
     * @param request
     * @param page
     * @param <T>
     * @return
     */
    protected static <T> void handleOrderBy(HttpServletRequest request, Page<T> page) {
        String fieldName = request.getParameter("fieldName");
        if (StringUtils.hasLength(fieldName)) {
            String sortType = request.getParameter("sortType");
            if (StringUtils.hasLength(sortType)) {
                List<OrderItem> orderItems;
                if ("desc".equalsIgnoreCase(sortType)) {
                    orderItems = Collections.singletonList(OrderItem.desc(StrUtil.toUnderlineCase(fieldName)));
                } else {
                    orderItems = Collections.singletonList(OrderItem.asc(StrUtil.toUnderlineCase(fieldName)));
                }
                page.setOrders(orderItems);
            }
        }
    }

    /**
     * request.getParameterMap->String,String[]转化为String,String
     *
     * @param request
     * @return
     */
    protected static Map<String, Object> requestParamMap(HttpServletRequest request) {
        Map<String, String[]> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<>(6);
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<?, ?> entry;
        String name;
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry<?, ?>) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (String s : values) {
                    value = s + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

    private static class DateEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            //转换yyyy-MM-dd HH:mm:ss格式数据
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            //如果不为空就格式化
            if (!StringUtils.isEmpty(text)) {
                try {
                    date = format.parse(text);
                } catch (ParseException e) {
                    //转换为yyyy-MM-dd格式数据
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        date = format.parse(text);
                    } catch (ParseException ignored) {
                    }
                }
            }
            setValue(date);
        }

    }
}
